<template>
  <el-container style="margin-top:50px">
    <el-header style="text-align:left !important"> {{currentNum+1}}. {{currentTitle.title}}</el-header>
    <el-container>
      <el-main>
        <el-row>
          <el-col :span="16">
            <div class="grid-content">
            </div>
            <div>
              <el-checkbox-group v-model="checkboxGroup">
                <el-checkbox-button v-for="option in options"
                                    :label="option.id"
                                    @change="changeChecked"
                                    :key="option.id">
                  {{option.option}}</el-checkbox-button>
              </el-checkbox-group>
            </div>
          </el-col>
          <el-col :span="8">
            <el-button-group style="margin-top:250px;">
              <el-button type="primary"
                         icon="el-icon-arrow-left"
                         @click="prevTitle">上一题</el-button>
              <el-button type="primary"
                         @click="nextTitle">下一题<i class="el-icon-arrow-right el-icon--right"></i></el-button>
              <el-button type="primary"
                         @click="submitTopic">提交<i class="el-icon-top"></i></el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </el-main>
      <el-aside width="500px">
        <el-row style="display:flex;height: 50px;">
          <div class="aside_message">答题卡</div>
          <div class="aside_message">
            <span>{{hour? hourString+':'+minuteString+':'+secondString : minuteString+':'+secondString}}</span>
          </div>
        </el-row>
        <el-row>
          <div style="display:flex;padding-left:20px;padding-top:20px;">
            <el-button type="primary"
                       circle
                       v-for="(title,i) in titleList"
                       :key="i"
                       @click="jumpTitle(i)"
                       style="width: 40px;height:40px;">{{i+1}}</el-button>
          </div>
        </el-row>
      </el-aside>
    </el-container>
  </el-container>
</template>

<script>
export default {
    // props: {
    //     remainTime: {
    //         // 倒计时间总秒数
    //         default: 60 * 20 + ''
    //     }
    // },

    data() {
        return {
            hour: '',
            minute: '',
            second: '',
            promiseTimer: '',
            remainTime: '0',
            checkboxGroup: [], //选中框
            options: [], //选项
            currentNum: 0, //当前题目在数组中的下标
            currentTitle: {}, //当前题的题干
            userid: -1,
            topicid: -1,
            titleList: [], //当前考试所有题
            topic: {
                name: '',
                categoryid: ''
            }, //当前考试对象
            myCheck: {
                num: -1,
                myOption: []
            },
            answers: [],
            correctAnswer: [],
            score: 0
        };
    },
    created() {
        (this.userid = localStorage.getItem('id')), (this.topicid = localStorage.getItem('topicid')), this.findTopic();
    },
    methods: {
        //计时器
        countDowm() {
            var self = this;
            clearInterval(this.promiseTimer);
            this.promiseTimer = setInterval(function () {
                if (self.hour === 0) {
                    if (self.minute !== 0 && self.second === 0) {
                        self.second = 59;
                        self.minute -= 1;
                    } else if (self.minute === 0 && self.second === 0) {
                        self.second = 0;
                        self.$emit('countDowmEnd', true);
                        clearInterval(self.promiseTimer);
                    } else {
                        self.second -= 1;
                    }
                } else {
                    if (self.minute !== 0 && self.second === 0) {
                        self.second = 59;
                        self.minute -= 1;
                    } else if (self.minute === 0 && self.second === 0) {
                        self.hour -= 1;
                        self.minute = 59;
                        self.second = 59;
                    } else {
                        self.second -= 1;
                    }
                }
            }, 1000);
        },
        formatNum(num) {
            return num < 10 ? '0' + num : '' + num;
        },
        //计算分数
        correct() {
            //console.log(this.titleList);
            let myAnswer = [];
            this.answers.forEach((element) => {
                let oneAnswer = '';
                element.myOption.forEach((item) => {
                    if (item == 0) {
                        oneAnswer = oneAnswer + 'A';
                    } else if (item == 1) {
                        oneAnswer = oneAnswer + 'B';
                    } else if (item == 2) {
                        oneAnswer = oneAnswer + 'C';
                    } else if (item == 3) {
                        oneAnswer = oneAnswer + 'D';
                    }
                });
                myAnswer.push(oneAnswer);
            });
            let score = 0;
            for (let i = 0; i < this.correctAnswer.length; i++) {
                let titleScore = 0;
                if (myAnswer[i].length > this.correctAnswer[i].length || myAnswer[i].length == 0) {
                    titleScore += 0;
                } else if (myAnswer[i].length < this.correctAnswer[i].length || myAnswer[i].length == this.correctAnswer[i].length) {
                    let count = 0;
                    let flag = 0;
                    let oneOption = myAnswer[i].toString();
                    for (let j = 0; j < oneOption.length; j++) {
                        //  console.log(this.correctAnswer[i], '------', oneOption, '----', oneOption.charAt(j));
                        // console.log(this.correctAnswer[i].indexOf(oneOption.charAt(j)));
                        if (this.correctAnswer[i].indexOf(oneOption.charAt(j)) == -1) {
                            flag = 1;
                        } else {
                            count = count + 1;
                        }
                    }
                    //console.log("count",count,"flag",flag);
                    if (0 < count && count < this.correctAnswer[i].length && flag == 0) {
                        titleScore += 5;
                    }
                    if (0 < count < this.correctAnswer[i].length && flag == 1) {
                        titleScore += 0;
                    }
                    if (count == this.correctAnswer[i].length) {
                        titleScore += 10;
                    }
                }
                score += titleScore;
            }
            this.score = score;
        },
        //提交分数
        submitTopic() {
            this.myCheck.num = this.currentNum;
            this.myCheck.myOption = this.checkboxGroup;
            this.intChage(this.myCheck);
            this.correct();
            let topicUserDto = {
                userid: this.userid,
                topicid: this.topicid,
                score: this.score
            };
            this.$axios
                .post('/api/topic/submitTopic', topicUserDto)
                .then((res) => {
                    if (res.data.code == 200) {
                      if(this.score<60){
                         this.$alert('您的分数是：'+this.score, '考试未通过', {
                            confirmButtonText: '确定',
                            callback: (action) => {
                                this.$router.push({ path: '/exam' });
                            }
                        });
                      }else{
                         this.$alert('您的分数是：'+this.score, '考试通过', {
                            confirmButtonText: '确定',
                            callback: (action) => {
                                this.$router.push({ path: '/exam' });
                            }
                        });
                      }
                       
                    }
                })
                .catch();
        },
        jumpTitle(i) {
            this.myCheck.num = this.currentNum;
            this.myCheck.myOption = this.checkboxGroup;
            this.intChage(this.myCheck);
            this.currentNum = i;
            this.checkboxGroup = this.answers[this.currentNum].myOption;
            this.changeTitle();
        },
        prevTitle() {
            if (this.currentNum == 0) {
                return;
            }
            this.myCheck.num = this.currentNum;
            this.myCheck.myOption = this.checkboxGroup;
            this.intChage(this.myCheck);
            this.currentNum = this.currentNum - 1;
            this.checkboxGroup = this.answers[this.currentNum].myOption;
            this.changeTitle();
        },
        nextTitle() {
            if (this.currentNum == this.titleList.length - 1) {
                return;
            }
            this.myCheck.num = this.currentNum;
            this.myCheck.myOption = this.checkboxGroup;
            this.intChage(this.myCheck);
            this.currentNum = this.currentNum + 1;
            this.checkboxGroup = this.answers[this.currentNum].myOption;
            this.changeTitle();
        },
        intChage(myCheck) {
            //console.log(myCheck);
            let index = myCheck.num;
            this.answers[index].myOption = myCheck.myOption;
        },
        changeChecked() {
            // console.log(this.checkboxGroup);
        },
        findCategory() {},
        changeTitle() {
            this.currentTitle = this.titleList[this.currentNum];
            this.options = [
                {
                    id: 0,
                    option: this.titleList[this.currentNum].optionA
                },
                {
                    id: 1,
                    option: this.titleList[this.currentNum].optionB
                },
                {
                    id: 2,
                    option: this.titleList[this.currentNum].optionC
                },
                {
                    id: 3,
                    option: this.titleList[this.currentNum].optionD
                }
            ];
        },
        findTopic() {
            this.$axios
                .get('/api/topic/findTopicByUserIdAndTopicId/' + this.userid + '/' + this.topicid)
                .then((res) => {
                    this.topic.name = res.data.data.name;
                    this.topic.categoryid = res.data.data.categoryid;
                    this.titleList = JSON.parse(res.data.data.content);
                    //计时器初始化
                    let time = res.data.data.time * 60;
                    this.remainTime = time.toString();
                    if (this.remainTime > 0) {
                        this.hour = Math.floor((this.remainTime / 3600) % 24);
                        this.minute = Math.floor((this.remainTime / 60) % 60);
                        this.second = Math.floor(this.remainTime % 60);
                        this.countDowm();
                    }
                    //答案初始化
                    for (let i = 0; i < this.titleList.length; i++) {
                        this.answers.push({ num: i, myOption: [] });
                    }
                    //获取正确答案
                    this.titleList.forEach((element) => {
                        this.correctAnswer.push(element.answer);
                    });
                    //第一次请求需执行换题方法（从没题到第一题）
                    this.changeTitle();
                })
                .catch();
        }
    },
    computed: {
        hourString() {
            return this.formatNum(this.hour);
        },
        minuteString() {
            return this.formatNum(this.minute);
        },
        secondString() {
            return this.formatNum(this.second);
        }
    }
};
</script>
<style scoped>
.aside_message {
    width: 50%;
    line-height: 50px;
}
.el-header,
.el-footer {
    background-color: white;
    color: #333;
    text-align: center;
    line-height: 60px;
}

.el-aside {
    background-color: white;
    color: #333;
    text-align: center;
    line-height: 200px;
    border: 1px solid #dcdfe6;
}

.el-main {
    background-color: white;
    color: #333;
    text-align: center;
    line-height: 160px;
}

body > .el-container {
    margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
    line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
    line-height: 320px;
}
.el-col-24 {
    width: 100%;
    line-height: 50px;
    text-align: left;
    margin-left: 60px;
}
.grid-content-option {
    border-radius: 4px;
    min-height: 36px;
    /* margin-left: 30px; */
}

</style>